// pages/feedback/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: [
      {
        id: 0,
        value: '商品反馈',
        isActive: true
      },
    ],
    chooseImgs: [], //选择图片的路径存
    textVal: '', //文本描述
  },

  UpLoadImgs: [],

  handleTabItemChange(e) {
    // console.log(e);
    //获取被点击的标题索引
    let {index} = e.detail;
    //修改原数组
    // console.log(this.data);
    let {tabs} = this.data
    tabs.forEach((v,i) => i==index?v.isActive=true:v.isActive=false)
    this.setData({
      tabs
    })
  },

  handleChooseImg() {
    wx.chooseImage({
      count: 9,
      sizeType: ['original','compressed'],
      sourceType: ['album','camera'], //图片来源
      success: (result)=>{
        this.setData({
          chooseImgs: [...this.data.chooseImgs, ...result.tempFilePaths]
        })
        
      },
    });
  },

  handleRemoveImg(e) {
    let {index} = e.currentTarget.dataset
    let {chooseImgs} = this.data
    chooseImgs.splice(index,1)
    this.setData({
      chooseImgs
    })
  },

  handleTextInput(e) {
    // console.log(e);
    this.setData({
      textVal: e.detail.value
    })

  },

  handleFormSubmit() {
    let {textVal, chooseImgs} = this.data

    if (!textVal.trim()) {
      wx.showToast({
        title: '输入非法',
        icon: 'none',
        mask: true,
      });
      return
    }
//遍历数组，依次上传

    wx.showLoading({
      title: "正在上传",
      mask: true,
    });

    //判断有没有上传图片
    if (chooseImgs.length) {
    chooseImgs.forEach((v,i) => {
    wx.uploadFile({
      //上传的地方
      url: "https://img.coolcr.cn/api/upload", 
      filePath: v,
      name: "image",
      formData: {},
      success: result => {
        // console.log(result);
        let url = JSON.parse(result.data).url
        console.log(url);
        this.UpLoadImgs.push(url)

        
        //所有图片上传完 i = len-1
        if (i === chooseImgs.length - 1) {
          console.log("把文本的内容和外网的图片数组 提交的后台");
          wx.hideLoading();
          // 重置页面
          this.setData({
            textVal: '',
            chooseImgs: []
          })

          //返回上一个页面
          wx.navigateBack({
            delta: 1
          });

          wx.showToast({
            title: '反馈已经收到，我们会尽快处理的',
            icon: 'none',
          });
        }
      }
      }
    );
  })
  } else {
    console.log("徐晓林最可爱");
    wx.hideLoading();
    wx.navigateBack({
      delta: 1
    });
  }
  },


})